<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item label="电表名称" prop="electricName">
            <el-input
              v-model="baTable.form.items!.electricName"
              placeholder="请输入电表名称"
            />
          </el-form-item>
          <el-form-item label="电表地址" prop="electricAddr">
            <el-input
              v-model="baTable.form.items!.electricAddr"
              placeholder="请输入电表地址"
            />
          </el-form-item>
          <el-form-item label="电表编号" prop="electricCode">
            <el-input
              v-model="baTable.form.items!.electricCode"
              aria-disabled="true"
              disabled
            />
            <div class="block-help">电表编号将按规则自动生成</div>
          </el-form-item>
          <el-form-item label="电表类型" prop="electricType">
            <el-select
              v-model="baTable.form.items!.electricType"
              placeholder="请选择电表类型"
            >
              <el-option
                v-for="item in electric.type"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictLabel"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用能类型" prop="electricLabel">
            <el-select
              v-model="baTable.form.items!.electricLabel"
              placeholder="请选择用能类型"
            >
              <el-option
                v-for="item in electric.typeLabel"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue - 0"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属网关" prop="gatewayName">
            <el-select
              v-model="baTable.form.items!.gatewayName"
              ref="gatewayRef"
              placeholder="请选择网关"
              @change="selectGateway"
              value-key="id"
            >
              <el-option
                v-for="item in state.gatewayOptions"
                :key="item.id"
                :label="item.gatewayName"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="心跳时间" prop="electricPant">
            <el-input-number
              v-model="baTable.form.items!.electricPant"
              :step="1000"
              aria-disabled="true"
              disabled
            />
            <div class="block-help" style="width: 100%">
              选择网关时将自动填写
            </div>
          </el-form-item>
          <el-form-item label="品牌型号" prop="brandModel">
            <el-input
              v-model="baTable.form.items!.brandModel"
              placeholder="请输入品牌型号"
            />
          </el-form-item>
          <el-form-item label="规约" prop="statute">
            <el-input
              v-model="baTable.form.items!.statute"
              placeholder="请输入规约"
            />
          </el-form-item>
          <el-form-item label="尺寸" prop="electricSize">
            <el-input
              v-model="baTable.form.items!.electricSize"
              placeholder="请输入尺寸"
            />
          </el-form-item>
          <el-form-item label="波特率" prop="baudRate">
            <el-input
              v-model="baTable.form.items!.baudRate"
              placeholder="请输入波特率"
            />
          </el-form-item>
          <el-form-item label="SIM卡号" prop="simCode">
            <el-input
              v-model="baTable.form.items!.simCode"
              placeholder="请输入SIM卡号"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="baTable.form.items!.electricRemark"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          {{ baTable.form.operate === "itemAdd" ? "确定并新增下一项" : "确定" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import _ from "lodash";
import { reactive, ref, inject, onMounted, onBeforeUnmount } from "vue";
import type baTableClass from "@/utils/baTable";
import type { ElForm, FormItemRule, FormRules } from "element-plus";
import FormItem from "@/components/formItem/index.vue";
import { useUser } from "@/store/backend/SysM/user";
import { getDictData } from "@/utils/common"; // 导入表格api方法生成器
import { ElMessage, ElMessageBox } from "element-plus";

type Option = {
  id: number;
  label: string;
  children: Option[];
};
const user = useUser();
//接受来自父组件的注入
const baTable = inject("baTable") as baTableClass;
const formRef = ref<InstanceType<typeof ElForm>>();
const dictionary = inject("dictionary") as any;
const gateway = inject("gateway") as any;
const cabinet = inject("cabinet") as any;
const site = inject("site") as any;
const dictOperation = inject("dictOperation") as any;
const electric = inject("electric") as any;

const gatewayRef = ref();

const state: {
  siteOptions: Option[];
  deptTypeOptions: any[];
  cabinetOptions: any[];
  gatewayOptions: any[];
} = reactive({
  siteOptions: [], //部门列表
  deptTypeOptions: [], //部门类型列表
  cabinetOptions: [], //机柜列表
  gatewayOptions: [], //网关列表
});
const rules = reactive<FormRules>({
  electricName: [
    { required: true, message: "电表名称不能为空", trigger: "blur" },
  ],
  electricAddr: [
    { required: true, message: "电表地址不能为空", trigger: "blur" },
  ],
  // electricCode: [
  //   { required: true, message: "电表编号不能为空", trigger: "blur" },
  // ],
  // type: [{ required: true, message: "电表类型不能为空", trigger: "blur" }],
  electricLabel: [
    { required: true, message: "用能类型不能为空", trigger: "blur" },
  ],
  gatewayName: [
    { required: true, message: "所属网关不能为空", trigger: "blur" },
  ],
});

//获取字典
const getDictionary = () => {
  //获取站点类型的字典
  dictOperation.getDictionary(site, "sys_site_type", "siteType", "type");
};
getDictionary();

//获取网关数据列表
const getGatewayList = () => {
  gateway.getList({ pageSize: 100000 }).then((res: any) => {
    state.gatewayOptions = res;
    console.log("state.gatewayOptions", state.gatewayOptions);
  });
};

//获取字典值
const getDistrictNum = (val: string) => {
  let len = site.type.length;
  for (let i = 0; i < len; ) {
    if (site.type[i].dictLabel === val) {
      return site.type[i].dictValue - 0;
    } else {
      i++;
    }
  }
};
//将机柜（点位）挂在站点之下
const putElectricUnderSite = () => {
  //首先获取机柜的点位id作为站点的父级站点id
  let gatewaType = getDistrictNum("网关");
  let electricType = getDistrictNum("电表");

  site
    .getFilterList({
      siteName: baTable.form.items!.gatewayName,
      siteType: getDistrictNum("网关"),
    })
    .then((res: any) => {
      let addSiteParams = {
        siteName: baTable.form.items!.electricName, //网关类型站点名称
        siteType: electricType, //站点类型
        siteOrder: 1, //顺序默认为1
        parentId: res[0].siteId, //网关类型站点id
        parentName: baTable.form.items!.gatewayName,
      };
      console.log("将电表挂在网关之下", res, addSiteParams);
      site
        .addSite(addSiteParams)
        .then((res: any) => {
          console.log("完成挂载");
        })
        .catch((err: any) => {
          console.log("挂载失败");
        });
    });
};
//删除之前挂载到站点的机柜
const deleteSite = (obj: any) => {
  console.log("判断是否需要删除之前的数据", obj, baTable.form.items);
  if (obj.parentName !== baTable.form.items!.gatewayName) {
    //如果修改的是不同一个站点下
    site.delete({ id: obj.siteId }).then((res: any) => {
      console.log("删除之前挂载到站点的机柜", res);
      //删除原先的机柜后挂载到新的站点
      putElectricUnderSite();
    });
  } else {
    console.log("不修改");
  }
};
//修改之前机柜上级节点
const changeParentSite = (obj: any) => {
  if (obj.parentName !== baTable.form.items!.gatewayName) {
    //如果修改的是不同一个站点下
    let newData = _.cloneDeep(obj);
    site
      .getFilterList({
        siteName: baTable.form.items!.gatewayName,
        siteType: getDistrictNum("网关"),
      })
      .then((res: any) => {
        newData.parentName = baTable.form.items!.gatewayName;
        newData.parentId = res[0].siteId; //站点父级id
        site
          .editSite(newData)
          .then((res: any) => {})
          .catch((err: any) => {});
      });
  } else {
    console.log("不修改");
  }
};

//判断站点类型为电表的数据是否存在
const isSite = () => {
  console.log("临时数据", baTable.form.items);
  site
    .getFilterList({
      siteName: baTable.form.items!.electricName,
      siteType: getDistrictNum("电表"),
    })
    .then((res: any) => {
      console.log("判断站点类型为电表是否存在", res);
      if (res.length > 0) {
        console.log("已经存在的电表需要修改上级数据", res[0]);
        //已经存在个体商户需要删除
        // deleteSite(res[0]);
        changeParentSite(res[0]);
      } else {
        console.log("不存在该电表需要挂载");
        //不存在该个体商户需要挂载
        putElectricUnderSite();
      }
    });
};

//获取electricRef的选择数据
const getRefValue = () => {
  ElMessageBox.confirm("是否确认该网关", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      //确认修改
      isSite();
    })
    .catch(() => {});
};

//选择网关
const selectGateway = (value: any) => {
  baTable.form.items!.gatewayName = value.gatewayName;
  baTable.form.items!.gatewayId = value.id;
  baTable.form.items!.electricPant = value.gatewayPant;
  console.log("选择网关", value, baTable.form.items);
};

//编辑表单保留原始网关名称待查站点
const keepOriginsiteName = () => {
  baTable.form.operate !== "edit"
    ? (electric.editsiteName = "")
    : (electric.editsiteName = baTable.form.items!.electricName);
};
//判断上级站点名称是否进行了修改
const isSameSiteName = () => {
  if (baTable.form.operate === "edit" && baTable.form.items!.gatewayName) {
    gateway
      .getfilterById({ siteId: baTable.form.items!.gatewayId })
      .then((res: any) => {
        if (baTable.form.items!.gatewayName !== res.gatewayName) {
          baTable.form.items!.gatewayName = res.gatewayName;
        }
      });
  }
};

//显现网关名称
onMounted(() => {
  getGatewayList(); //获取网关数据列表
  setTimeout(() => {
    keepOriginsiteName(); //编辑表单保留原始设备名称待查站点
    isSameSiteName(); //判断上级站点名称是否进行了修改
  }, 500);
});

onBeforeUnmount(() => {
  electric.editsiteName = "";
});
</script>
<style lang="scss" scoped>
.el-scrollbar {
  height: 500px;
  overflow-y: auto;
}
</style>
